package com.atmilan.quartz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.Constants;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.SyncStatusEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.dto.paolo.PaoloProductResDTO;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.SystemConfig;
import com.atmilan.quartz.model.entity.paolo.PaoloProduct;
import com.atmilan.quartz.model.entity.paolo.PaoloProductSku;
import com.atmilan.quartz.service.*;
import com.atmilan.quartz.utils.product.PaoloProductUtil;
import com.atmilan.quartz.utils.source.SourcePaoloProductUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class IPaoloSyncServiceImpl implements IPaoloSyncService {

    @Autowired
    ISystemConfigService systemConfigService;
    @Autowired
    IPaoloProductService paoloProductService;
    @Autowired
    IPaoloProductSkuService paoloProductSkuService;
    @Autowired
    IStoreProductService storeProductService;
    @Autowired
    SourcePaoloProductUtil sourcePaoloProductUtil;
    @Autowired
    PaoloProductUtil paoloProductUtil;

    @Override
    public Boolean syncPaoloProduct() {
        paoloProductService.deleteAll();
        paoloProductSkuService.deleteAll();

        int pageNo = 1;
        int pageCount = 1;
        long start = System.currentTimeMillis();
        while (pageNo <= pageCount) {
            PaoloProductResDTO paoloProductResDTO = paoloProductUtil.selectPaolo();
            if (null == paoloProductResDTO) {
                log.info("--------------- paolo获取商品接口请求失败 ---------------");
                continue;
            }
            // 保存商品和sku
            saveGoods(paoloProductResDTO);
            log.info("--------------- paolo远程抓取数据, 第: {} 页,  总共: {} 页, 总耗时: {} 分  ---------------", pageNo, pageCount, (int) ((System.currentTimeMillis() - start) / 1000 / 60));
            pageNo ++;
        }
        return true;
    }

    /**
     * 功能描述: paolo商品源数据保存
     * @Param: [paoloProductResDTO]
     * @Return: void
     * @Author: wangzh
     * @Date: 2023/2/13 16:41
     */
    private void saveGoods(PaoloProductResDTO paoloProductResDTO) {
        List<PaoloProduct> goodsList = new ArrayList<>();
        List<PaoloProductSku> skuList = new ArrayList<>();
        paoloProductResDTO.getProducts().forEach(good -> {
            if (CollectionUtils.isNotEmpty(good.getSizes())){
                good.getSizes().forEach(sku -> {
                    PaoloProductSku paoloProductSku = new PaoloProductSku();
                    paoloProductSku.setProductId(good.getProductId());
                    BeanUtils.copyProperties(sku, paoloProductSku);
                    skuList.add(paoloProductSku);
                });
            }
            PaoloProduct paoloProduct = new PaoloProduct();
            BeanUtils.copyProperties(good, paoloProduct);
            paoloProduct.setPriceIncludeVat(good.getPriceIncludeVat().equals("true"));
            paoloProduct.setProductLastUpdate(good.getProductLastUpdated());
            paoloProduct.setPhotos(JSON.toJSONString(good.getPhotos()));
            if (good.getIsCarryOver()) {
                paoloProduct.setSeason("Carryover");
            }
            goodsList.add(paoloProduct);
        });
        paoloProductService.saveBatch(goodsList);
        paoloProductSkuService.saveBatch(skuList);
    }

    @Override
    public Boolean pushPaoloProduct() {
        try {
            int count = paoloProductService.count();
            if (1000 > count) {
                systemConfigService.update(Wrappers.<SystemConfig>lambdaUpdate()
                        .eq(SystemConfig::getName, Constants.PAOLO_SYNC_STATUS)
                        .set(SystemConfig::getFormId, SyncStatusEnum.PUSH)
                        .set(SystemConfig::getUpdateTime, new Date()));
                log.info("--------------- PAOLO商品源数据, 少于规定条数, 不进行下发, 总条数为: {} ---------------", count);
                return false;
            }
            // 将所有paolo商品更新状态置为未更新
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct::getIsEurope, ProductTypeEnum.JULIAN.getCode())
                    .set(StoreProduct::getUpdateFlag, false));

            // 商品更新操作
            int pageNo = 1;
            int pageSize = 100;
            int maxPage = (count + pageSize - 1) / pageSize;
            log.info("--------------- 开始分页查询paolo商品源数据, 本次更新总条数为: {} ---------------", count);

            long start = System.currentTimeMillis();
            while (pageNo <= maxPage) {
                try {
                    PageHelper.startPage(pageNo, pageSize);
                    List<PaoloProduct> paoloProducts = paoloProductService.list();
                    buildProduct(paoloProducts);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                log.info("--------------- paolo下发商品到数据库, 当前页数: {}, 总页数: {}, 耗时: {} 分 ---------------", pageNo, maxPage, (int) ((System.currentTimeMillis() - start) / 1000 / 60));
                pageNo ++;
            }
            // 图搜删除
            storeProductService.delSeachImage(ProductTypeEnum.JULIAN);
            // 下架所有未更新数据
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct::getIsEurope, ProductTypeEnum.JULIAN.getCode())
                    .eq(StoreProduct::getUpdateFlag, false)
                    .eq(StoreProduct::getIsShow, true)
                    .eq(StoreProduct::getIsDel, false)
                    .set(StoreProduct::getIsShow, false)
                    .set(StoreProduct::getStock, 0)
                    .set(StoreProduct::getLastPushTime, new Date())
                    .set(StoreProduct::getIsTusou, false));
            // 下架所有sku库存
            storeProductService.downloadSku(ProductTypeEnum.JULIAN.getCode());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 功能描述: 商品构建
     * @Param: [paoloProducts]
     * @Return: void
     * @Author: wangzh
     * @Date: 2023/2/14 18:07
     */
    private void buildProduct(List<PaoloProduct> paoloProducts) {
        try {
            for (PaoloProduct paoloProduct : paoloProducts) {
                // 商品没有图片跳转
                JSONArray photos = JSONArray.parseArray(paoloProduct.getPhotos());
                if (CollectionUtils.isEmpty(photos)) {
                    log.info("--------------- 该商品: {} 没有图片, 不进行下放 ---------------", paoloProduct.getProductId());
                    continue;
                }
                if (paoloProduct.getRetailPrice().compareTo(BigDecimal.ZERO) < 1) {
                    log.info("--------------- 该商品: {} 售价异常, 不进行下放 ---------------", paoloProduct.getProductId());
                    continue;
                }
                // 该商品sku列表
                List<PaoloProductSku> skus = paoloProductSkuService.list(Wrappers.<PaoloProductSku>lambdaQuery()
                        .eq(PaoloProductSku::getProductId, paoloProduct.getProductId())
                        .isNotNull(PaoloProductSku::getSize)
                        .gt(PaoloProductSku::getStock, 0));
                if (CollectionUtils.isEmpty(skus)){
                    continue;
                }
                // 库存计算
                int stock = 0;
                for (PaoloProductSku sku : skus) {
                    stock += sku.getStock();
                }

                // 构建实体
                StoreProductCrmebRequest storeProductCrmebRequest = sourcePaoloProductUtil.buildPaoloProduct(paoloProduct, skus);
                // 数据保存
                StoreProduct storeProduct = storeProductService.getByBarCode(storeProductCrmebRequest.getBarCode(), storeProductCrmebRequest.getSuppliersId(), storeProductCrmebRequest.getKeyword());
                boolean crmebUpdate = true;
                if (null != storeProduct && null != storeProduct.getLastPushTime()) {
                    long txyye = (System.currentTimeMillis() - storeProduct.getLastPushTime().getTime()) / 1000 / 60;
                    if (60 > txyye) {
                        log.info("--------------- 该商品: {} 上次paolo更新时间: {} 小于一小时, 不进行更新 ---------------", storeProductCrmebRequest.getBarCode(), storeProduct.getLastPushTime());
                        crmebUpdate = false;
                        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                                .eq(StoreProduct::getId, storeProduct.getId())
                                .set(StoreProduct::getUpdateFlag, true));
                    }
                }
                if (crmebUpdate) {
                    storeProductService.saveOtProduct(storeProductCrmebRequest, storeProduct, stock);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
